from sqlalchemy.orm import Session, joinedload
from typing import List, Optional
from app.models.models import Account
from app.database.repository.general_repository import GeneralRepository
from app.core.pagination import Pageable, Page

class AccountRepository(GeneralRepository[Account]):
    """
    账户仓库类，处理账户相关的数据库操作
    """
    
    def __init__(self, db: Session):
        super().__init__(db, Account)
    
    def find_with_user(self, account_id: int) -> Optional[Account]:
        """
        查询账户并预加载用户信息
        """
        return self.db.query(Account).options(joinedload(Account.user)).filter(Account.id == account_id).first()
    
    def find_all_with_user(self, skip: int = 0, limit: int = 100) -> List[Account]:
        """
        查询所有账户并预加载用户信息
        """
        return self.db.query(Account).options(joinedload(Account.user)).offset(skip).limit(limit).all()
    
    def find_by_user_id(self, user_id: int) -> Optional[Account]:
        """
        根据用户ID查找账户
        """
        return self.db.query(Account).filter(Account.user_id == user_id).first()
    
    def find_all_with_pagination(self, pageable: Pageable) -> Page:
        """
        分页查询所有账户，并预加载用户信息
        """
        skip, limit = pageable.to_skip_limit()
        total = self.db.query(Account).count()
        accounts = self.db.query(Account).options(joinedload(Account.user)).offset(skip).limit(limit).all()
        
        return Page.create(
            items=accounts,
            currentPage=pageable.page,
            pageSize=pageable.pageSize,
            totalCount=total
        )
    
    def update_balance(self, account_id: int, amount: float) -> Optional[Account]:
        """
        更新账户余额
        amount可以是正数（充值）或负数（扣款）
        """
        account = self.find_one(account_id)
        if account:
            account.balance += amount
            self.db.commit()
            self.db.refresh(account)
        return account